'use strict';

module.exports = {
  _before: async function() {
    // 获取客户端信息
    this.clientInfo = this.getClientInfo();
    console.log('match-object _before 初始化完成');
  },

  /**
   * 获取我的比赛列表 - 修改为从matches表获取比赛系列数据
   */
  getMyMatches: async function(params = {}) {
      try {
        console.log('getMyMatches 开始执行，参数:', params);
        
        // 直接使用user-service验证token
        const token = this.getUniIdToken();
        console.log('获取到的token:', token ? '存在' : '不存在');
        
        if (!token) {
          return {
            code: -1,
            message: '未登录或登录状态已过期'
          };
        }
        
        const userService = uniCloud.importObject('user-service');
        const verifyResult = await userService.verifyToken({ token });
        
        if (verifyResult.code !== 0) {
          return {
            code: -1,
            message: verifyResult.message || '身份验证失败'
          };
        }
        
        const userId = verifyResult.data.userId;

        // 获取分页参数
        const { page = 1, pageSize = 20, status } = params;
        const skip = (page - 1) * pageSize;

        const db = uniCloud.database();
        
        // 第一步：查询matches表获取用户创建的比赛系列
        const matchCollection = db.collection('matches');
        let matchQuery = matchCollection.where({ publisher_id: userId });
        
        // 如果有状态筛选
        if (status && status !== 'all') {
          matchQuery = matchQuery.where({ status: status });
        }
        
        const matchResult = await matchQuery
          .orderBy('create_time', 'desc')
          .limit(pageSize)
          .skip(skip)
          .get();

        if (matchResult.data.length === 0) {
          return {
            code: 0,
            data: {
              list: [],
              total: 0,
              page: page,
              pageSize: pageSize
            },
            message: '查询成功'
          };
        }

        // 第二步：获取这些比赛的日程数据
        const matchIds = matchResult.data.map(match => match._id);
        
        const scheduleCollection = db.collection('match_schedules');
        const scheduleResult = await scheduleCollection
          .where({
            match_id: db.command.in(matchIds)
          })
          .orderBy('date', 'asc')
          .get();
        
        // 第二步半：获取准确的申请数据（从match_applications集合）
        const applicationCollection = db.collection('match_applications');
        const applicationResult = await applicationCollection
          .where({
            match_id: db.command.in(matchIds)
          })
          .get();
        
        // 按比赛ID和时段ID分组申请数据
        const applicationsByMatch = {};
        applicationResult.data.forEach(app => {
          const matchId = app.match_id;
          const slotId = app.slot_id;
          
          if (!applicationsByMatch[matchId]) {
            applicationsByMatch[matchId] = {};
          }
          if (!applicationsByMatch[matchId][slotId]) {
            applicationsByMatch[matchId][slotId] = [];
          }
          applicationsByMatch[matchId][slotId].push(app);
        });

        // 第三步：获取用户查看状态数据
        const viewCollection = db.collection('user_series_views');
        const viewResult = await viewCollection
          .where({
            user_id: userId,
            series_id: db.command.in(matchIds)
          })
          .get();
        
        const viewStatusMap = {};
        viewResult.data.forEach(view => {
          viewStatusMap[view.series_id] = view;
        });

        // 第四步：处理数据，将日程关联到对应的比赛
        const processedMatches = matchResult.data.map(match => {
          // 获取该比赛的所有日程
          const matchSchedules = scheduleResult.data.filter(schedule => schedule.match_id === match._id);
          
          // 统计总体数据
          let totalMatches = 0;
          let totalApplications = 0;
          let pendingApplications = 0;
          let confirmedApplications = 0;
          
          // 获取该比赛的申请数据
          const matchApplications = applicationsByMatch[match._id] || {};
          
          // 处理日程数据
          const schedules = matchSchedules.map(schedule => {
            // 处理时段数据
            const sessions = (schedule.time_slots || []).map(slot => {
              totalMatches += 1;
              
              // 从match_applications集合获取准确的申请统计
              const slotApplications = matchApplications[slot.slot_id] || [];
              const slotTotalApplications = slotApplications.length;
              const slotPendingApplications = slotApplications.filter(app => app.status === 'pending').length;
              const slotConfirmedApplications = slotApplications.filter(app => 
                app.status === 'confirmed' || app.status === 'selected'
              ).length;
              
              totalApplications += slotTotalApplications;
              pendingApplications += slotPendingApplications;
              confirmedApplications += slotConfirmedApplications;
              
              // 转换为前端期望的字段结构，使用准确的申请数据
              return {
                session_id: slot.slot_id || slot._id,
                start_time: slot.start_time,
                end_time: slot.end_time,
                field: slot.field || slot.venue,
                home_team: slot.home_team,
                away_team: slot.away_team,
                category: slot.category,
                positions: slot.referee_requirements || {},
                status: slot.status || 'open',
                applications: slotApplications, // 使用准确的申请数据
                total_applications: slotTotalApplications,
                pending_applications: slotPendingApplications,
                confirmed_applications: slotConfirmedApplications
              };
            });
            
            return {
              schedule_id: schedule._id,
              date: schedule.date,
              venue: schedule.venue,
              sessions: sessions
            };
          });
          
          // 计算新场次信息
          const viewStatus = viewStatusMap[match._id];
          let newMatchCount = 0;
          let lastUpdateTime = match.update_time;
          
          // 获取最新的日程更新时间
          if (matchSchedules.length > 0) {
            const latestScheduleTime = Math.max(...matchSchedules.map(s => new Date(s.update_time || s.create_time).getTime()));
            lastUpdateTime = new Date(latestScheduleTime);
          }
          
          if (viewStatus) {
            // 比较场次数量变化
            if (totalMatches > viewStatus.last_known_match_count) {
              newMatchCount = totalMatches - viewStatus.last_known_match_count;
            }
            
            // 如果有新的更新时间，也标记为有新内容
            if (lastUpdateTime && viewStatus.last_known_update_time) {
              const lastKnownTime = new Date(viewStatus.last_known_update_time);
              if (lastUpdateTime > lastKnownTime) {
                newMatchCount = Math.max(newMatchCount, 1); // 至少标记1个新场次
              }
            }
          } else {
            // 用户从未查看过，所有场次都是新的
            newMatchCount = totalMatches;
          }

          // 返回完整的比赛系列数据
          return {
            _id: match._id,
            title: match.title,
            start_date: match.start_date,
            end_date: match.end_date,
            location: match.location,
            status: match.status,
            match_type: match.match_type,
            level: match.level,
            publisher_id: match.publisher_id,
            create_time: match.create_time,
            update_time: match.update_time,
            // 日程数据
            schedules: schedules,
            // 统计数据
            total_matches: totalMatches,
            total_applications: totalApplications,
            pending_applications: pendingApplications,
            confirmed_applications: confirmedApplications,
            // 新增的新场次标记字段
            newMatchCount: newMatchCount,
            lastUpdateTime: lastUpdateTime,
            hasNewMatches: newMatchCount > 0
          };
        });

        return {
          code: 0,
          data: {
            list: processedMatches,
            total: processedMatches.length,
            page: page,
            pageSize: pageSize
          },
          message: '查询成功'
        };

      } catch (error) {
        console.error('getMyMatches 执行失败:', error);
        return {
          code: -1,
          message: '查询失败: ' + error.message
        };
      }
  },

  /**
   * 获取比赛列表（公开访问）
   */
  getMatchList: async function(params = {}) {
    try {
      const { page = 1, limit = 20, match_type, level, search } = params;
      const skip = (page - 1) * limit;

      const db = uniCloud.database();
      const matchCollection = db.collection('matches');
    
      // 构建查询条件 - 只显示已发布的比赛
      let where = { status: 'published' };
        
      if (match_type) {
        where.match_type = match_type;
      }
      
      if (level) {
        where.level = level;
        }
        
      if (search) {
        // 使用正则表达式进行模糊搜索
        where.$or = [
          { title: new RegExp(search, 'i') },
          { location: new RegExp(search, 'i') }
        ];
      }
      
      // 查询比赛列表
      const result = await matchCollection
        .where(where)
        .orderBy('create_time', 'desc')
        .skip(skip)
        .limit(limit)
        .get();

      // 获取总数
      const countResult = await matchCollection.where(where).count();
      
      if (result.data.length === 0) {
        return {
          code: 0,
          message: '获取成功',
          data: {
            list: [],
            total: countResult.total,
            page,
            limit,
            hasMore: false
          }
        };
      }

      // 获取比赛的日程数据并计算统计信息
      const matchIds = result.data.map(match => match._id);
      const scheduleCollection = db.collection('match_schedules');
      const scheduleResult = await scheduleCollection
        .where({
          match_id: db.command.in(matchIds)
        })
        .get();

      // 获取准确的申请数据（从match_applications集合）
      const applicationCollection = db.collection('match_applications');
      const applicationResult = await applicationCollection
        .where({
          match_id: db.command.in(matchIds)
        })
        .get();

      // 按比赛ID分组申请数据
      const applicationsByMatch = {};
      applicationResult.data.forEach(app => {
        const matchId = app.match_id;
        if (!applicationsByMatch[matchId]) {
          applicationsByMatch[matchId] = [];
        }
        applicationsByMatch[matchId].push(app);
      });

      // 处理比赛数据，添加统计信息
      const processedList = result.data.map(match => {
        // 获取该比赛的所有日程
        const matchSchedules = scheduleResult.data.filter(schedule => schedule.match_id === match._id);
        
        // 统计总体数据
        let totalMatches = 0;
        let totalApplications = 0;
        
        // 遍历日程计算场次数据
        matchSchedules.forEach(schedule => {
          if (schedule.time_slots && schedule.time_slots.length > 0) {
            totalMatches += schedule.time_slots.length;
          }
        });
        
        // 从match_applications集合获取准确的报名数据
        const matchApplications = applicationsByMatch[match._id] || [];
        totalApplications = matchApplications.filter(app => app.status !== 'cancelled').length;
        
        return {
        ...match,
          match_format: match.match_format || '十一人制',
          // 添加统计数据
          total_matches: totalMatches,
          total_applications: totalApplications
        };
      });
      
        return {
          code: 0,
        message: '获取成功',
        data: {
          list: processedList,
          total: countResult.total,
          page,
          limit,
          hasMore: countResult.total > page * limit
        }
      };
    } catch (error) {
      console.error('获取比赛列表失败:', error);
      return {
        code: -1,
        message: '获取比赛列表失败'
      };
    }
  },

  /**
   * 创建比赛
   */
  createMatch: async function(matchData) {
    try {
      // 直接使用user-service验证token
      const token = this.getUniIdToken();
      if (!token) {
      return {
          code: -1,
          message: '未登录或登录状态已过期'
      };
    }

      const userService = uniCloud.importObject('user-service');
      const verifyResult = await userService.verifyToken({ token });
      
      if (verifyResult.code !== 0) {
        return {
          code: -1,
          message: verifyResult.message || '身份验证失败'
        };
      }
      
      const userId = verifyResult.data.userId;

      const db = uniCloud.database();
      const matchCollection = db.collection('matches');

      // 准备比赛数据
      const now = new Date();
      const newMatch = {
        ...matchData,
        publisher_id: userId,
        organizer_id: userId, // 兼容字段，确保两个字段都有值
        create_time: now,
        update_time: now,
        status: matchData.status || 'draft',
        applicants: []
      };

      // 插入数据
      const result = await matchCollection.add(newMatch);
      
      // 发送比赛创建通知给全平台用户（不论比赛状态）
      try {
        const notificationService = uniCloud.importObject('notification-service');
        
        // 获取全平台用户（不限认证状态和角色）
        const userCollection = db.collection('users');
        const usersResult = await userCollection.field({
          _id: true
        }).get();
        
        if (usersResult.data && usersResult.data.length > 0) {
          const userIds = usersResult.data.map(user => user._id);
          
          // 根据比赛状态设置不同的通知内容
          let notificationTitle, notificationContent;
          
          if (matchData.status === 'published') {
            notificationTitle = `新比赛发布：${matchData.title}`;
            notificationContent = `${matchData.title} 已正式发布！比赛时间：${matchData.date}，地点：${matchData.location}。快来报名参与执裁吧！`;
          } else {
            notificationTitle = `新比赛创建：${matchData.title}`;
            notificationContent = `${matchData.title} 已创建，比赛时间：${matchData.date}，地点：${matchData.location}。敬请关注后续日程安排！`;
          }
          
          // 批量发送通知
          await notificationService.batchSendNotification({
            userIds: userIds,
            type: 'match_publish',
            title: notificationTitle,
            content: notificationContent,
            relatedId: result.id,
            senderId: userId,
            extraData: {
              jump_type: 'match_detail',
              jump_url: `/packgeCompetition/competition/detail?id=${result.id}`,
              match_id: result.id,
              match_title: matchData.title,
              match_status: matchData.status
            }
          });
          
          console.log(`比赛创建通知已发送给全平台 ${userIds.length} 名用户`);
        }
      } catch (notifyError) {
        console.error('发送比赛创建通知失败:', notifyError);
        // 不影响比赛创建的主流程
      }
      
        return {
          code: 0,
        message: '比赛创建成功',
        data: {
          _id: result.id,
          ...newMatch
        }
      };
    } catch (error) {
      console.error('创建比赛失败:', error);
      return {
        code: -2,
        message: '创建比赛失败'
      };
    }
  },

  /**
   * 更新比赛
   */
  updateMatch: async function(matchId, updateData) {
    try {
      // 直接使用user-service验证token
      const token = this.getUniIdToken();
      if (!token) {
        return {
          code: -1,
          message: '未登录或登录状态已过期'
        };
      }

      const userService = uniCloud.importObject('user-service');
      const verifyResult = await userService.verifyToken({ token });
      
      if (verifyResult.code !== 0) {
        return {
          code: -1,
          message: verifyResult.message || '身份验证失败'
        };
      }

      const userId = verifyResult.data.userId;

      const db = uniCloud.database();
      const matchCollection = db.collection('matches');

      // 检查比赛是否存在且为当前用户发布
      const matchResult = await matchCollection.doc(matchId).get();
      if (!matchResult.data.length) {
        return {
          code: -1,
          message: '比赛不存在'
        };
      }
      
      const match = matchResult.data[0];
      if (match.publisher_id !== userId) {
        return {
          code: -1,
          message: '无权限修改此比赛'
        };
      }

      // 更新数据
      const result = await matchCollection.doc(matchId).update({
        ...updateData,
        update_time: new Date()
      });
      
      return {
        code: 0,
        message: '比赛更新成功',
        data: result
      };
    } catch (error) {
      console.error('更新比赛失败:', error);
      return {
        code: -2,
        message: '更新比赛失败'
      };
    }
  },

  /**
   * 删除比赛
   */
  deleteMatch: async function(matchId) {
    try {
      // 直接使用user-service验证token
      const token = this.getUniIdToken();
      if (!token) {
        return {
          code: -1,
          message: '未登录或登录状态已过期'
        };
      }

      const userService = uniCloud.importObject('user-service');
      const verifyResult = await userService.verifyToken({ token });
      
      if (verifyResult.code !== 0) {
        return {
          code: -1,
          message: verifyResult.message || '身份验证失败'
        };
      }
      
      const userId = verifyResult.data.userId;

      const db = uniCloud.database();
      const matchCollection = db.collection('matches');
      
      // 检查比赛是否存在且为当前用户发布
      const matchResult = await matchCollection.doc(matchId).get();
      if (!matchResult.data.length) {
      return {
          code: -1,
          message: '比赛不存在'
        };
      }
      
      const match = matchResult.data[0];
      if (match.publisher_id !== userId) {
        return {
          code: -1,
          message: '无权限删除此比赛'
        };
      }

      // 删除比赛
      await matchCollection.doc(matchId).remove();

      return {
        code: 0,
        message: '比赛删除成功'
      };
    } catch (error) {
      console.error('删除比赛失败:', error);
      return {
        code: -2,
        message: '删除比赛失败'
      };
    }
  },

  /**
   * 获取比赛详情
   */
  getMatchDetail: async function(matchId) {
    try {
      const db = uniCloud.database();
      const matchCollection = db.collection('matches');

      const result = await matchCollection.doc(matchId).get();
      
      if (!result.data.length) {
        return {
          code: -1,
          message: '比赛不存在'
        };
      }

      // 处理比赛数据，确保赛制字段存在
      const matchData = {
        ...result.data[0],
        match_format: result.data[0].match_format || '十一人制'
      };

      return {
        code: 0,
        message: '获取成功',
        data: matchData
      };
    } catch (error) {
      console.error('获取比赛详情失败:', error);
      return {
        code: -1,
        message: '获取比赛详情失败'
      };
    }
  },

  /**
   * 报名参加裁判
   */
  applyForReferee: async function(params) {
    try {
      // 直接使用user-service验证token
      const token = this.getUniIdToken();
      if (!token) {
      return {
          code: -1,
          message: '未登录或登录状态已过期'
      };
    }

      const userService = uniCloud.importObject('user-service');
      const verifyResult = await userService.verifyToken({ token });
      
      if (verifyResult.code !== 0) {
      return {
          code: -1,
          message: verifyResult.message || '身份验证失败'
        };
      }
      
      const userId = verifyResult.data.userId;
      const { matchId, positionId, message } = params;
      
      const db = uniCloud.database();
      const matchCollection = db.collection('matches');
      const applicationsCollection = db.collection('referee_applications');
      
      // 检查比赛是否存在
      const matchResult = await matchCollection.doc(matchId).get();
      if (!matchResult.data.length) {
        return {
          code: -1,
          message: '比赛不存在'
        };
      }
      
      // 检查是否已经报名
      const existingApplication = await applicationsCollection.where({
        match_id: matchId,
        user_id: userId,
        position_id: positionId
      }).get();
      
      if (existingApplication.data.length > 0) {
        return {
          code: -1,
          message: '您已经报名了这个职位'
        };
      }
      
      // 创建报名记录
      const application = {
        match_id: matchId,
        user_id: userId,
        position_id: positionId,
        message: message || '',
        status: 'pending',
        create_time: new Date()
      };
      
      const result = await applicationsCollection.add(application);

        return {
          code: 0,
        message: '报名成功',
          data: {
          _id: result.id,
          ...application
          }
        };
    } catch (error) {
      console.error('报名失败:', error);
      return {
        code: -2,
        message: '报名失败'
      };
    }
  },

  /**
   * 申请做裁判（兼容旧接口名称）
   */
  applyReferee: async function(params) {
    // 参数格式转换，兼容旧版本调用
    const convertedParams = {
      matchId: params.match_id || params.matchId,
      positionId: params.position || params.positionId || 'referee',
      message: params.message || ''
    };
    return await this.applyForReferee(convertedParams);
  },

  /**
   * 获取审核申请列表
   */
  getReviewApplications: async function(matchId) {
    try {
      // 直接使用user-service验证token
      const token = this.getUniIdToken();
      if (!token) {
      return {
          code: -1,
          message: '未登录或登录状态已过期'
        };
      }
      
      const userService = uniCloud.importObject('user-service');
      const verifyResult = await userService.verifyToken({ token });
      
      if (verifyResult.code !== 0) {
      return {
          code: -1,
          message: verifyResult.message || '身份验证失败'
        };
      }
      
      const userId = verifyResult.data.userId;

      const db = uniCloud.database();
      const matchCollection = db.collection('matches');
      const applicationsCollection = db.collection('match_applications');
      
      // 检查比赛是否存在且为当前用户发布
      const matchResult = await matchCollection.doc(matchId).get();
      if (!matchResult.data.length) {
      return {
          code: -1,
          message: '比赛不存在'
        };
      }
      
      const match = matchResult.data[0];
      if (match.publisher_id !== userId) {
        return {
          code: -1,
          message: '无权限查看申请列表'
        };
      }
      
      // 获取申请列表
      const result = await applicationsCollection
        .where({ match_id: matchId })
        .orderBy('create_time', 'desc')
        .get();
        
        return {
          code: 0,
        message: '获取成功',
        data: result.data
      };
    } catch (error) {
      console.error('获取申请列表失败:', error);
      return {
        code: -2,
        message: '获取申请列表失败'
      };
    }
  },

  /**
   * 审核申请
   */
  reviewApplication: async function(params) {
    try {
      // 直接使用user-service验证token
      const token = this.getUniIdToken();
      if (!token) {
        return {
          code: -1,
          message: '未登录或登录状态已过期'
        };
      }
      
      const userService = uniCloud.importObject('user-service');
      const verifyResult = await userService.verifyToken({ token });
      
      if (verifyResult.code !== 0) {
      return {
          code: -1,
          message: verifyResult.message || '身份验证失败'
        };
      }
      
      const userId = verifyResult.data.userId;
      const { application_id, applicationId, status, review_note, reviewMessage } = params;
      const finalApplicationId = application_id || applicationId;
      const finalReviewMessage = review_note || reviewMessage;
      
      const db = uniCloud.database();
      const applicationsCollection = db.collection('match_applications');
      const matchCollection = db.collection('matches');
      
      // 获取申请详情
      const applicationResult = await applicationsCollection.doc(finalApplicationId).get();
      if (!applicationResult.data.length) {
      return {
          code: -1,
          message: '申请不存在'
        };
      }
      
      const application = applicationResult.data[0];
      
      // 检查比赛是否为当前用户发布
      const matchResult = await matchCollection.doc(application.match_id).get();
      if (!matchResult.data.length) {
        return {
          code: -1,
          message: '比赛不存在'
        };
      }

      const match = matchResult.data[0];
      if (match.publisher_id !== userId) {
        return {
          code: -1,
          message: '无权限审核此申请'
        };
      }
      
      // 更新申请状态
      await applicationsCollection.doc(finalApplicationId).update({
        status: status,
        review_note: finalReviewMessage || '',
        review_time: new Date(),
        reviewer_id: userId
      });
      
      // 发送审核结果通知给申请人
      try {
        const notificationService = uniCloud.importObject('notification-service');
        
        let notificationTitle, notificationContent;
        if (status === 'approved' || status === 'selected') {
          notificationTitle = '比赛申请审核通过';
          notificationContent = `恭喜！您的比赛申请已通过审核。比赛：${match.title}，请按时参加比赛。`;
        } else if (status === 'rejected') {
          notificationTitle = '比赛申请审核未通过';
          notificationContent = `很遗憾，您的比赛申请未通过审核。比赛：${match.title}。${finalReviewMessage ? '原因：' + finalReviewMessage : ''}`;
        }
        
        if (notificationTitle) {
          await notificationService.sendNotification({
            userId: application.user_id,
            type: 'match_review',
            title: notificationTitle,
            content: notificationContent,
            relatedId: application.match_id,
            senderId: userId
          });
          
          console.log(`比赛申请审核通知已发送给用户 ${application.user_id}`);
        }
      } catch (notifyError) {
        console.error('发送审核通知失败:', notifyError);
        // 不影响审核的主流程
      }
      
      return {
        code: 0,
        message: '审核完成',
        data: {
          application_id: finalApplicationId,
          status,
          review_note: finalReviewMessage
        }
      };
    } catch (error) {
      console.error('审核申请失败:', error);
      return {
        code: -2,
        message: '审核申请失败'
      };
    }
  },

  /**
   * 获取我的申请列表
   */
  getMyApplications: async function() {
    try {
      // 直接使用user-service验证token
      const token = this.getUniIdToken();
      if (!token) {
        return {
          code: -1,
          message: '未登录或登录状态已过期'
        };
      }

      const userService = uniCloud.importObject('user-service');
      const verifyResult = await userService.verifyToken({ token });
      
      if (verifyResult.code !== 0) {
        return {
          code: -1,
          message: verifyResult.message || '身份验证失败'
        };
      }

      const userId = verifyResult.data.userId;

      const db = uniCloud.database();
      const applicationsCollection = db.collection('match_applications');
      const schedulesCollection = db.collection('match_schedules');
      const matchesCollection = db.collection('matches');  // 修改：使用matches表

      console.log('getMyApplications 开始执行，用户ID:', userId);

      // 1. 获取用户的申请列表
      const applicationResult = await applicationsCollection
        .where({ user_id: userId })
        .orderBy('apply_time', 'desc')
        .get();

      const applications = applicationResult.data || [];
      console.log('查询到的申请记录数量:', applications.length);

      if (applications.length === 0) {
        return {
          code: 0,
          message: '获取成功',
          data: []
        };
      }

      // 2. 获取相关的日程信息
      const scheduleIds = [...new Set(applications.map(app => app.schedule_id).filter(id => id))];
      console.log('需要查询的日程IDs:', scheduleIds);
      
      const scheduleResult = await schedulesCollection
        .where({
          _id: db.command.in(scheduleIds)
        })
        .get();

      console.log('查询到的日程数量:', scheduleResult.data.length);

      // 3. 获取相关的比赛信息（从matches表）
      const matchIds = [...new Set(scheduleResult.data.map(schedule => schedule.match_id).filter(id => id))];
      console.log('需要查询的比赛IDs:', matchIds);
      
      const matchResult = await matchesCollection
        .where({
          _id: db.command.in(matchIds)
        })
        .field({
          _id: true,
          title: true
        })
        .get();

      console.log('查询到的比赛信息数量:', matchResult.data.length);

      // 4. 构建数据映射
      const scheduleMap = {};
      const matchMap = {};
      
      scheduleResult.data.forEach(schedule => {
        scheduleMap[schedule._id] = schedule;
      });
      
      matchResult.data.forEach(match => {
        matchMap[match._id] = match;
      });

      // 5. 合并信息到申请记录
      const enrichedApplications = applications.map(app => {
        const schedule = scheduleMap[app.schedule_id];
        let matchInfo = null;
        let slotInfo = null;
        let scheduleApplication = null;
        
        if (schedule) {
          // 获取比赛基本信息
          matchInfo = matchMap[schedule.match_id];
          
          // 查找对应的时段信息
          if (app.slot_id && schedule.time_slots) {
            slotInfo = schedule.time_slots.find(slot => slot.slot_id === app.slot_id);
            
            // 查找日程中对应的申请记录，获取application_id
            if (slotInfo && slotInfo.applications) {
              scheduleApplication = slotInfo.applications.find(scheduleApp => 
                scheduleApp.user_id === app.user_id && 
                scheduleApp.position === app.position &&
                scheduleApp.status !== 'cancelled'
              );
            }
          }
        }

        return {
          ...app,
          // 【修复】添加application_id字段映射，用于取消申请
          application_id: scheduleApplication?.application_id || app._id,
          
          // 比赛名称
          match_name: matchInfo?.title || '未知比赛',
          // 比赛日期
          match_date: schedule?.date || '',
          // 比赛时段
          match_time_slot: slotInfo ? `${slotInfo.start_time}-${slotInfo.end_time}` : '时段未定',
          // 比赛主队vs客队
          match_teams: slotInfo ? `${slotInfo.home_team || '主队'} vs ${slotInfo.away_team || '客队'}` : '对阵待定',
          // 比赛场地（时段场地）
          match_field: slotInfo?.field || schedule?.venue || '场地待定',
          // 报名岗位
          applied_position: app.position || '未知岗位',
          
          // 新增：支持查看选派表的字段
          session_id: app.slot_id || '', // 时段ID，用于查询选派表
          schedule_id: app.schedule_id || '', // 日程ID
          match_id: schedule?.match_id || '', // 比赛ID
          has_schedule: app.status === 'confirmed', // 是否有选派表可查看
          
          // 保持原有的match_info结构用于兼容前端
          match_info: {
            title: slotInfo ? `${slotInfo.home_team || '主队'} vs ${slotInfo.away_team || '客队'}` : (matchInfo?.title || '未知比赛'),
            match_date: schedule?.date || '',
            match_time: slotInfo?.start_time || '',
            end_time: slotInfo?.end_time || '',
            home_team: slotInfo?.home_team || '主队',
            away_team: slotInfo?.away_team || '客队',
            location: slotInfo?.field || schedule?.venue || '场地待定'
          }
        };
      });

      console.log('处理完成，返回数据条数:', enrichedApplications.length);

      return {
        code: 0,
        message: '获取成功',
        data: enrichedApplications
      };
      
    } catch (error) {
      console.error('获取我的申请失败:', error);
      return {
        code: -2,
        message: '获取我的申请失败: ' + error.message
      };
    }
  },

  /**
   * 获取时段申请列表
   */
  getSessionApplications: async function(params) {
    try {
      // 直接使用user-service验证token
      const token = this.getUniIdToken();
      if (!token) {
        return {
          code: -1,
          message: '未登录或登录状态已过期'
        };
      }

      const userService = uniCloud.importObject('user-service');
      const verifyResult = await userService.verifyToken({ token });
      
      if (verifyResult.code !== 0) {
        return {
          code: -1,
          message: verifyResult.message || '身份验证失败'
        };
      }

      const userId = verifyResult.data.userId;

      const db = uniCloud.database();
      const applicationsCollection = db.collection('match_applications');
      const matchCollection = db.collection('matches');
      const userCollection = db.collection('uni-id-users');

      // 兼容不同的参数格式
      let matchId, sessionId;
      if (typeof params === 'string') {
        // 兼容旧格式：直接传递sessionId
        sessionId = params;
      } else if (params && typeof params === 'object') {
        matchId = params.match_id;
        sessionId = params.session_id;
      }

      // 构建查询条件
      let whereCondition = {};
      if (matchId) {
        whereCondition.match_id = matchId;
      }
      if (sessionId) {
        whereCondition.session_id = sessionId;
      }

      // 如果没有查询条件，返回错误
      if (Object.keys(whereCondition).length === 0) {
        return {
          code: -1,
          message: '缺少查询参数'
        };
      }

      // 检查权限：只有比赛发布者可以查看申请列表
      if (matchId) {
        const matchResult = await matchCollection.doc(matchId).get();
        if (!matchResult.data.length) {
          return {
            code: -1,
            message: '比赛不存在'
          };
        }

        const match = matchResult.data[0];
        if (match.publisher_id !== userId) {
          return {
            code: -1,
            message: '无权限查看申请列表'
          };
        }
      }

      // 获取申请列表
      const applicationResult = await applicationsCollection
        .where(whereCondition)
        .orderBy('apply_time', 'desc')
        .get();

      const applications = applicationResult.data || [];

      // 获取申请用户信息
      if (applications.length > 0) {
        const userIds = [...new Set(applications.map(app => app.user_id))];
        const userResult = await userCollection
          .where({
            _id: db.command.in(userIds)
          })
          .field({
            _id: true,
            nickname: true,
            username: true,
            avatar: true,
            mobile: true,
            email: true
          })
          .get();

        const userMap = {};
        userResult.data.forEach(user => {
          userMap[user._id] = user;
        });

        // 合并用户信息到申请记录
        applications.forEach(app => {
          app.user_info = userMap[app.user_id] || {};
        });
      }

      return {
        code: 0,
        message: '获取成功',
        data: {
          applications: applications,
          session: {
            session_id: sessionId,
            match_id: matchId
          }
        }
      };
    } catch (error) {
      console.error('获取时段申请失败:', error);
      return {
        code: -2,
        message: '获取时段申请失败'
      };
    }
  },

  /**
   * 标记用户已查看系列赛
   */
  markSeriesAsViewed: async function(params) {
    try {
      console.log('markSeriesAsViewed 开始执行，参数:', params);
      
      // 直接使用user-service验证token
      const token = this.getUniIdToken();
      if (!token) {
        return {
          code: -1,
          message: '未登录或登录状态已过期'
        };
      }
      
      const userService = uniCloud.importObject('user-service');
      const verifyResult = await userService.verifyToken({ token });
      
      if (verifyResult.code !== 0) {
        return {
          code: -1,
          message: verifyResult.message || '身份验证失败'
        };
      }
      
      const userId = verifyResult.data.userId;
      const { seriesId } = params;
      
      if (!seriesId) {
        return {
          code: -1,
          message: '系列赛ID不能为空'
        };
      }

      const db = uniCloud.database();
      
      // 获取当前系列赛的最新统计信息
      const matchCollection = db.collection('matches');
      const scheduleCollection = db.collection('match_schedules');
      
      // 获取比赛基本信息
      const matchResult = await matchCollection.doc(seriesId).get();
      if (!matchResult.data.length) {
        return {
          code: -1,
          message: '系列赛不存在'
        };
      }
      
      const match = matchResult.data[0];
      
      // 获取该系列赛的所有日程和场次数量
      const scheduleResult = await scheduleCollection
        .where({ match_id: seriesId })
        .get();
      
      let totalMatches = 0;
      let latestUpdateTime = match.update_time;
      
      scheduleResult.data.forEach(schedule => {
        if (schedule.time_slots && schedule.time_slots.length > 0) {
          totalMatches += schedule.time_slots.length;
        }
        
        // 获取最新的更新时间
        const scheduleUpdateTime = new Date(schedule.update_time || schedule.create_time);
        if (scheduleUpdateTime > latestUpdateTime) {
          latestUpdateTime = scheduleUpdateTime;
        }
      });

      const viewCollection = db.collection('user_series_views');
      const now = new Date();
      
      // 尝试更新现有记录，如果不存在则创建新记录
      const existingView = await viewCollection
        .where({
          user_id: userId,
          series_id: seriesId
        })
        .get();
      
      if (existingView.data.length > 0) {
        // 更新现有记录
        const viewRecord = existingView.data[0];
        await viewCollection.doc(viewRecord._id).update({
          last_view_time: now,
          view_count: db.command.inc(1),
          last_known_match_count: totalMatches,
          last_known_update_time: latestUpdateTime,
          update_time: now
        });
        
        console.log('更新查看记录成功，用户:', userId, '系列赛:', seriesId);
      } else {
        // 创建新记录
        await viewCollection.add({
          user_id: userId,
          series_id: seriesId,
          last_view_time: now,
          view_count: 1,
          last_known_match_count: totalMatches,
          last_known_update_time: latestUpdateTime,
          create_time: now,
          update_time: now
        });
        
        console.log('创建查看记录成功，用户:', userId, '系列赛:', seriesId);
      }
      
      return {
        code: 0,
        message: '标记查看成功',
        data: {
          user_id: userId,
          series_id: seriesId,
          view_time: now,
          match_count: totalMatches
        }
      };
      
    } catch (error) {
      console.error('标记系列赛查看失败:', error);
      return {
        code: -2,
        message: '标记查看失败: ' + error.message
      };
    }
  }
}; 